package com.google.code.mergeinformer.util;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Class for accessing HttpServletRequest and related objects
 *
 * @author Dmitry Golubev
 */
public class ServletUtils {

    private ServletUtils() {
    }

    @SuppressWarnings("unchecked")
    public static <T> T getSessionAttribute(HttpServletRequest request, String name, Class<T> clazz) {
        return (T) request.getSession().getAttribute(name);
    }

    public static Object getSessionAttribute(HttpServletRequest request, String name) {
        return getSessionAttribute(request, name, Object.class);
    }

    /**
     * Put attribute into user's session
     *
     * @param name  name of attribute
     * @param value value of attribute to put
     * @return previous value of attribute, null if not present
     */
    public static Object putSessionAttribute(HttpServletRequest request, String name, Object value) {
        final Object oldValue = getSessionAttribute(request, name);
        request.getSession().setAttribute(name, value);
        return oldValue;
    }

    public static void setCacheHeaders(HttpServletResponse response, int seconds, boolean mustRevalidate) {
        // HTTP 1.0 header
        response.setDateHeader("Expires", System.currentTimeMillis() + seconds * 1000L);
        // HTTP 1.1 header
        response.setHeader("Cache-Control", "max-age=" + seconds + (mustRevalidate ? ", must-revalidate" : ""));
    }
}
